from rest_framework import serializers
from .models import Course
from apps.users.models import User


class CourseListSerializer(serializers.ModelSerializer):
    """课程列表序列化器"""
    teacher_name = serializers.CharField(source='teacher.real_name', read_only=True)
    teacher_id = serializers.IntegerField(source='teacher.id', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)
    enrollment_rate = serializers.SerializerMethodField()
    available_slots = serializers.SerializerMethodField()

    class Meta:
        model = Course
        fields = [
            'id', 'course_code', 'course_name', 'teacher_name', 'teacher_id', 'credit_hours',
            'class_hours', 'capacity', 'enrolled_count', 'semester', 'status',
            'status_display', 'enrollment_rate', 'available_slots', 'start_date',
            'end_date', 'classroom', 'created_at', 'updated_at'
        ]

    def get_enrollment_rate(self, obj):
        """计算选课率"""
        if obj.capacity > 0:
            return round((obj.enrolled_count / obj.capacity) * 100, 2)
        return 0

    def get_available_slots(self, obj):
        """计算剩余名额"""
        return max(0, obj.capacity - obj.enrolled_count)


class CourseDetailSerializer(serializers.ModelSerializer):
    """课程详情序列化器"""
    teacher_name = serializers.CharField(source='teacher.real_name', read_only=True)
    teacher_id = serializers.IntegerField(source='teacher.id', read_only=True)
    teacher_id_display = serializers.CharField(source='teacher.teacher_id', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = Course
        fields = [
            'id', 'course_code', 'course_name', 'description', 'teacher', 'teacher_id',
            'teacher_name', 'teacher_id_display', 'credit_hours', 'class_hours',
            'capacity', 'enrolled_count', 'course_image', 'semester', 'status',
            'status_display', 'start_date', 'end_date', 'schedule', 'classroom',
            'created_at', 'updated_at'
        ]


class CourseCreateUpdateSerializer(serializers.ModelSerializer):
    """课程创建/更新序列化器"""

    class Meta:
        model = Course
        fields = [
            'course_code', 'course_name', 'description', 'teacher',
            'credit_hours', 'class_hours', 'capacity', 'course_image',
            'semester', 'status', 'start_date', 'end_date', 'schedule', 'classroom'
        ]

    def validate_course_code(self, value):
        """验证课程编号唯一性"""
        instance = getattr(self, 'instance', None)
        if instance and instance.course_code == value:
            return value

        if Course.objects.filter(course_code=value).exists():
            raise serializers.ValidationError("课程编号已存在")
        return value

    def validate_teacher(self, value):
        """验证教师"""
        if value.role != 'teacher':
            raise serializers.ValidationError("只能选择教师角色的用户")
        if value.status != 'active':
            raise serializers.ValidationError("只能选择激活状态的教师")
        return value

    def validate_capacity(self, value):
        """验证课程容量"""
        if value <= 0:
            raise serializers.ValidationError("课程容量必须大于0")

        instance = getattr(self, 'instance', None)
        if instance and value < instance.enrolled_count:
            raise serializers.ValidationError(f"课程容量不能小于已选课人数({instance.enrolled_count})")

        return value

    def validate_credit_hours(self, value):
        """验证学分"""
        if value <= 0:
            raise serializers.ValidationError("学分必须大于0")
        return value

    def validate_class_hours(self, value):
        """验证学时"""
        if value <= 0:
            raise serializers.ValidationError("学时必须大于0")
        return value

    def validate(self, data):
        """交叉验证"""
        start_date = data.get('start_date')
        end_date = data.get('end_date')

        if start_date and end_date and start_date >= end_date:
            raise serializers.ValidationError("开课日期必须早于结课日期")

        return data


class TeacherSimpleSerializer(serializers.ModelSerializer):
    """教师简单序列化器"""

    class Meta:
        model = User
        fields = ['id', 'real_name', 'teacher_id', 'department']